package org.javatribe.calculator.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.EventObject;
import java.util.List;

import javax.swing.*;

/**
 * Created by Wenxin on 2017/9/15.
 */
public class BaseFrame extends JFrame {

    private final static Logger logger = LoggerFactory.getLogger(BaseFrame.class);

    private final List<Handler> handlers = new ArrayList<>();

    private final ActionListener BUTTON_ACTION = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            EventWrapper eventWrapper = new EventWrapper(handlers, event, BaseFrame.this,event.getActionCommand());
            WorkThreadPool.getThreadPoolExecutorService().execute(() -> notifyToListener(eventWrapper));
        }
    };

    protected BaseFrame() throws HeadlessException {
        super();
    }

    protected void init() {
        //对成员变量中是swing组件的添加通知监听器的行为
        Field[] fields = getClass().getDeclaredFields();
        for (Field field : fields) {
            //为按钮添加通知监听器行为
            if (field.getType().equals(JButton.class)) {
                try {
                    field.setAccessible(true);
                    JButton button = (JButton) field.get(this);
                    button.addActionListener(this.BUTTON_ACTION);
                } catch (IllegalAccessException e) {
                    logger.error("add action listener failure", e);
                }
            }
        }
    }

    public boolean addHandler(Handler handler) {
        return handlers.add(handler);
    }

    public boolean addHandlers(List<Handler> handlers) {
        return this.handlers.addAll(handlers);
    }

    public void addHandler(int index, Handler handler) {
        handlers.add(index, handler);
    }

    public Handler removeHandler(int index) {
        return handlers.remove(index);
    }

    public boolean removeHandler(Handler handler) {
        return handlers.remove(handler);
    }

    protected void notifyToListener(EventWrapper eventWrapper) {
        eventWrapper.proccess();
    }

}
